
/** $Id: Amf3Codec.java 60 2009-06-15 08:47:09Z salbanese0080@gmail.com $ */

package org.aquiferserver.server.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;

/**
 * @author Seth Albanese
 * @version $Id: Amf3Codec.java 60 2009-06-15 08:47:09Z salbanese0080@gmail.com $
 */
public class Amf3Codec implements SerializationCodec {

	protected final Log logger = LogFactory.getLog( org.aquiferserver.server.net.Amf3Codec.class );
	
	private SerializationContext context;
	
	public <T> String encode( final T source) throws IOException
	{
		//final StringBuffer buffer = new StringBuffer();
		final ByteArrayOutputStream bout = new ByteArrayOutputStream();
		final Amf3Output amfOutput = new Amf3Output( context );
		
		amfOutput.setOutputStream( bout );
		amfOutput.writeObject( source );
		amfOutput.flush();
		amfOutput.close();
		
		final BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode( bout.toByteArray() );
	}
	
	public <T> T decode( final String source ) throws IOException, ClassNotFoundException
	{
		logger.debug( "Decoding " + source );
		final BASE64Decoder decoder = new BASE64Decoder();
		byte[] input = decoder.decodeBuffer( source );
		InputStream bIn = new ByteArrayInputStream( input );
		Amf3Input amfInput = new Amf3Input( context );
		amfInput.setInputStream( bIn );
		return (T) amfInput.readObject();
	}
	
	public void setSerializationContext( SerializationContext c )
	{
		context = c;
	}
	
}
